package com.ns.dcjh.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSONObject;
import com.bytedance.sdk.open.aweme.authorize.model.Authorization;
import com.bytedance.sdk.open.aweme.base.ImageObject;
import com.bytedance.sdk.open.aweme.base.MediaContent;
import com.bytedance.sdk.open.aweme.base.VideoObject;
import com.bytedance.sdk.open.aweme.share.Share;
import com.bytedance.sdk.open.douyin.DouYinOpenApiFactory;
import com.bytedance.sdk.open.douyin.DouYinOpenConfig;
import com.bytedance.sdk.open.douyin.api.DouYinOpenApi;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.ns.dcjh.bean.MessageEvent;
import com.ns.dcjh.constant.Constant;
import com.ns.dcjh.vo.DouYinVideoInfoVo;
import com.orhanobut.logger.Logger;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class DouYinUtils {

    private Context mContext;

    public DouYinUtils(Context context) {
        this.mContext = context;
    }

    //是否安装了抖音
    public static boolean isInstalled(Context context) {
        DouYinOpenApi api = DouYinOpenApiFactory.create((Activity) context);
        return api.isAppInstalled();
    }

    //分享
    public void share(DouYinVideoInfoVo vo) {

        if (vo.isUseImgs()) {
            if (vo.getImgs() == null || vo.getImgs().size() == 0) {
                ToastUtils.info(mContext, "请至少选择一张图片");
                return;
            }

            ArrayList<Bitmap> bitmapList = new ArrayList<>();

            for (Object object : vo.getImgs()) {
                try {
                    String image = (String) object;
                    String[] imageSplit = image.split(",");
                    if (imageSplit.length < 2) continue;
                    Bitmap bitmap = BitmapUtils.base64ToBitmap(imageSplit[1], mContext);
                    bitmapList.add(bitmap);
                } catch (Exception e) {
                    ToastUtils.info(mContext, e.getMessage());
                }
            }
            ArrayList<String> imageList = new ArrayList<>();

            BitmapUtils.bitmapSaveFileToStorage(bitmapList).subscribe(new Observer<File>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(File file) {
                    imageList.add(file.getAbsolutePath());
                }

                @Override
                public void onError(Throwable e) {
                    JSONObject extras = new JSONObject();
                    extras.put("errorCode", 1);
                    extras.put("errorMsg", "android处理图片异常");

                    MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_SHARE_CONTENT_TO_TT_RESP);
                    msgEvent.setExtras(extras);
                    EventBus.getDefault().post(msgEvent);
                }

                @Override
                public void onComplete() {
                    if (imageList.size() > 0) {
                        shareImages(imageList, vo.getTag());
                    } else {
                        JSONObject extras = new JSONObject();
                        extras.put("errorCode", 2);
                        extras.put("errorMsg", "抖音分享的图片数量为0");

                        MessageEvent msgEvent = new MessageEvent(Constant.MSG_EVENT_SHARE_CONTENT_TO_TT_RESP);
                        msgEvent.setExtras(extras);
                        EventBus.getDefault().post(msgEvent);
                    }
                }
            });

        } else {
            startDownloadVideo(vo);
        }

    }

    private void startDownloadVideo(DouYinVideoInfoVo vo) {
        String video = StringUtils.isEmpty(vo.getVideo()) ? vo.getVideoNb() : vo.getVideo();
        if (StringUtils.isEmpty(video)) {
            ToastUtils.info(mContext, "无效的视频地址");
            return;
        }

        File file = FileUtils.getFile("video", "mp4");

        LoadingUtils mLoading = LoadingUtils.create(mContext).show();
        FileDownloader
                .getImpl()
                .create(video)
                .setPath(file.getAbsolutePath())
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        mLoading.dismiss();
                        shareVideo(file.getAbsolutePath(), vo.getTag());
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        mLoading.dismiss();
                        Logger.d("下载视频失败");
                        vo.setVideo(vo.getVideoNb());
                        if (!StringUtils.equals(vo.getVideo(), vo.getVideoNb())) {
                            startDownloadVideo(vo);
                        } else {
                            ToastUtils.info(mContext, "下载视频失败");
                        }
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        mLoading.dismiss();
                    }
                })
                .start();

    }


    //分享照片
    private void shareImages(ArrayList<String> imageList, String tag) {
        Share.Request request = new Share.Request();
        ArrayList<String> newImageList = new ArrayList<>();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
            for (String filePath : imageList) {
                File file = new File(filePath);
                Uri contentUri = FileProvider.getUriForFile(mContext, "com.ns.dcjh.fileprovider", file);
                // 授权给微信访问路径
                mContext.grantUriPermission("com.ss.android.ugc.aweme", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                String imagePath = contentUri.toString();
                newImageList.add(imagePath);
            }
        }else {
            newImageList = imageList;
        }
        ArrayList<String> hashTags = new ArrayList<>();
        hashTags.add(tag);
        ImageObject imageObject = new ImageObject();
        imageObject.mImagePaths = newImageList;
        MediaContent content = new MediaContent();
        content.mMediaObject = imageObject;
        request.mMediaContent = content;
        request.mState = "ss";
        request.mHashTagList = hashTags;
        DouYinOpenApi api = DouYinOpenApiFactory.create((Activity) mContext);
        if(api != null) {
            api.share(request);
        } else {
            ((Activity)mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.info(mContext, "未知错误");
                }
            });
        }
    }

    private void shareVideo(String video, String tag) {
        Share.Request request = new Share.Request();

        ArrayList<String> hashTags = new ArrayList<>();
        hashTags.add(tag);

        ArrayList<String> videoPaths = new ArrayList<>();

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
            File file = new File(video);
            Uri contentUri = FileProvider.getUriForFile(mContext, "com.ns.dcjh.fileprovider", file);
            // 授权给微信访问路径
            mContext.grantUriPermission("com.ss.android.ugc.aweme", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            String imagePath = contentUri.toString();
            videoPaths.add(imagePath);
        }else {
            videoPaths.add(video);
        }

        VideoObject videoObject = new VideoObject();
        videoObject.mVideoPaths = videoPaths;

        MediaContent content = new MediaContent();
        content.mMediaObject = videoObject;
        request.mMediaContent = content;
        request.mState = "ss";
        request.mHashTagList = hashTags;
        DouYinOpenApi api = DouYinOpenApiFactory.create((Activity) mContext);
        if(api != null) {
            api.share(request);
        } else {
            ((Activity)mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.info(mContext, "未知错误");
                }
            });
        }
    }


    public void authorize(String scope) {
        DouYinOpenApi api = DouYinOpenApiFactory.create((Activity) mContext);
        Authorization.Request request = new Authorization.Request();
        request.scope = scope;
        api.authorize(request);
    }

}
